package com.huangfuyi.process.actuator.threadpool;

import com.huangfuyi.process.entity.mainthread.EPInstance;
import com.huangfuyi.process.entity.monitor.EPMonitorSlowTaskCheckInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;

public class EPSlowThreadPool {

    private static final Logger log = Logger.getLogger("EPSlowThreadPool");

    private static final List<EPMainThread> SLOW_THREADS = new CopyOnWriteArrayList<>();

    // 检查核心线程池中各个线程运行任务的时长，并将运行超长任务的线程转移到慢任务线程集合
    public static void slowCheck(ArrayList<EPMonitorSlowTaskCheckInfo> checkResults) {
        List<EPMainThread> mainThreads = EPMainThreadPool.threads;
        int mainThreadCount = mainThreads.size();
        for (int i = mainThreadCount - 1; i >= 0; i--) {
            EPMainThread mainThread = mainThreads.get(i);
            EPInstance instance = mainThread.getInstance();
            try {
                if (mainThread.getStartTime() > 0 && System.currentTimeMillis() - mainThread.getStartTime() > 3 * 60 * 1000L) {
                    mainThread.markAsSlow();
                    mainThreads.remove(mainThread);
                    SLOW_THREADS.add(mainThread);
                    EPMonitorSlowTaskCheckInfo slowTaskCheckInfo = new EPMonitorSlowTaskCheckInfo();
                    // TODO: 2024-05-29 补全检查信息
                    checkResults.add(slowTaskCheckInfo);
                }
            } catch (Throwable t) {
                log.warning(String.format(Locale.ROOT, "慢线程检查：线程检查失败，线程名称：%s， 流程实例id：%s， 节点id：%s， 运行时id：%s", mainThread.getName(), instance.getId(), instance.getCurrentNodeId(), instance.getCurrentRunningId()));
            }
        }
        log.info(String.format(Locale.ROOT, "慢线程检查：检查结束。检查线程数量：%d， 慢线程数量：%d， 慢线程详情：%s", mainThreadCount, checkResults.size(), checkResults));

        // 释放执行完成的线程对象，等待垃圾回收器回收
        finishedSlowThreadClean();
    }

    // 释放完成执行的线程的引用
    private static void finishedSlowThreadClean() {
        for (int i = SLOW_THREADS.size() - 1; i >= 0 ; i--) {
            EPMainThread slowThread = SLOW_THREADS.get(i);
            if(!slowThread.isAlive()){
                SLOW_THREADS.remove(slowThread);
            }
        }
    }

    // 禁止创建实例
    private EPSlowThreadPool() {
    }
}
